package com.zq.qingzhu.service.impl;

import com.zq.qingzhu.bean.GoodsDetail;
import com.zq.qingzhu.bean.OrderItem;
import com.zq.qingzhu.bean.OrderRecord;
import com.zq.qingzhu.bean.StockNumDTO;
import com.zq.qingzhu.common.*;
import com.zq.qingzhu.controller.vo.*;
import com.zq.qingzhu.dao.GoodsDetailMapper;
import com.zq.qingzhu.dao.OrderItemMapper;
import com.zq.qingzhu.dao.OrderRecordMapper;
import com.zq.qingzhu.dao.ShopCartMapper;
import com.zq.qingzhu.service.OrderService;
import com.zq.qingzhu.util.BeanUtil;
import com.zq.qingzhu.util.NumberUtil;
import com.zq.qingzhu.util.PageQueryUtil;
import com.zq.qingzhu.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.groupingBy;

@Service
public class OrderServiceImpl implements OrderService {

	@Autowired
	private OrderRecordMapper orderRecordMapper;
	@Autowired
	private OrderItemMapper orderItemMapper;
	@Autowired
	private ShopCartMapper shoppingCartItemMapper;
	@Autowired
	private GoodsDetailMapper goodsDetailMapper;

	@Override
	public PageResult getOrdersPage(PageQueryUtil pageUtil) {
		List<OrderRecord> orders = orderRecordMapper.findOrderList(pageUtil);
		int total = orderRecordMapper.getTotalOrders(pageUtil);
		PageResult pageResult = new PageResult(orders, total, pageUtil.getLimit(), pageUtil.getPage());
		return pageResult;
	}

	@Override
	@Transactional
	public String updateOrderInfo(OrderRecord order) {
		OrderRecord temp = orderRecordMapper.selectByPrimaryKey(order.getId());
		//不为空且orderStatus>=0且状态为出库之前可以修改部分信息
		if (temp != null && temp.getStatus() >= 0 && temp.getStatus() < 3) {
			temp.setTotalPrice(order.getTotalPrice());
			temp.setUserAddress(order.getUserAddress());
			temp.setUpdateTime(new Date());
			if (orderRecordMapper.updateByPrimaryKeySelective(temp) > 0) {
				return ServiceResultEnum.SUCCESS.getResult();
			}
			return ServiceResultEnum.DB_ERROR.getResult();
		}
		return ServiceResultEnum.DATA_NOT_EXIST.getResult();
	}

	@Override
	@Transactional
	public String checkDone(Integer[] ids) {
//		查询所有的订单 判断状态 修改状态和更新时间
		List<OrderRecord> orders = orderRecordMapper.selectByPrimaryKeys(Arrays.asList(ids));
		String errorOrderNos = "";
		if (!CollectionUtils.isEmpty(orders)) {
			for (OrderRecord order : orders) {
//				if (order.getIsDeleted() == 1) {
//					errorOrderNos += order.getOrderNo() + " ";
//					continue;
//				}
				if (order.getStatus() != 1) {
					errorOrderNos += order.getOrderNo() + " ";
				}
			}
			if (StringUtils.isEmpty(errorOrderNos)) {
				//订单状态正常 可以执行配货完成操作 修改订单状态和更新时间
				if (orderRecordMapper.checkDone(Arrays.asList(ids)) > 0) {
					return ServiceResultEnum.SUCCESS.getResult();
				} else {
					return ServiceResultEnum.DB_ERROR.getResult();
				}
			} else {
				//订单此时不可执行出库操作
				if (errorOrderNos.length() > 0 && errorOrderNos.length() < 100) {
					return errorOrderNos + "订单的状态不是支付成功无法执行出库操作";
				} else {
					return "你选择了太多状态不是支付成功的订单，无法执行配货完成操作";
				}
			}
		}
		//未查询到数据 返回错误提示
		return ServiceResultEnum.DATA_NOT_EXIST.getResult();
	}

	@Override
	@Transactional
	public String checkOut(Integer[] ids) {
		//查询所有的订单 判断状态 修改状态和更新时间
		List<OrderRecord> orders = orderRecordMapper.selectByPrimaryKeys(Arrays.asList(ids));
		String errorOrderNos = "";
		if (!CollectionUtils.isEmpty(orders)) {
			for (OrderRecord order : orders) {
//				if (order.getIsDeleted() == 1) {
//					errorOrderNos += order.getOrderNo() + " ";
//					continue;
//				}
				if (order.getStatus() != 1 && order.getStatus() != 2) {
					errorOrderNos += order.getOrderNo() + " ";
				}
			}
			if (StringUtils.isEmpty(errorOrderNos)) {
				//订单状态正常 可以执行出库操作 修改订单状态和更新时间
				if (orderRecordMapper.checkOut(Arrays.asList(ids)) > 0) {
					return ServiceResultEnum.SUCCESS.getResult();
				} else {
					return ServiceResultEnum.DB_ERROR.getResult();
				}
			} else {
				//订单此时不可执行出库操作
				if (errorOrderNos.length() > 0 && errorOrderNos.length() < 100) {
					return errorOrderNos + "订单的状态不是支付成功或配货完成无法执行出库操作";
				} else {
					return "你选择了太多状态不是支付成功或配货完成的订单，无法执行出库操作";
				}
			}
		}
		//未查询到数据 返回错误提示
		return ServiceResultEnum.DATA_NOT_EXIST.getResult();
	}

	@Override
	@Transactional
	public String closeOrder(Integer[] ids) {
		//查询所有的订单 判断状态 修改状态和更新时间
		List<OrderRecord> orders = orderRecordMapper.selectByPrimaryKeys(Arrays.asList(ids));
		String errorOrderNos = "";
		if (!CollectionUtils.isEmpty(orders)) {
			for (OrderRecord order : orders) {
				// isDeleted=1 一定为已关闭订单
//				if (order.getIsDeleted() == 1) {
//					errorOrderNos += order.getOrderNo() + " ";
//					continue;
//				}
				//已关闭或者已完成无法关闭订单
				if (order.getStatus() == 4 || order.getStatus() < 0) {
					errorOrderNos += order.getOrderNo() + " ";
				}
			}
			if (StringUtils.isEmpty(errorOrderNos)) {
				//订单状态正常 可以执行关闭操作 修改订单状态和更新时间
				if (orderRecordMapper.closeOrder(Arrays.asList(ids), OrderStatusEnum.ORDER_CLOSED_BY_JUDGE.getOrderStatus()) > 0) {
					return ServiceResultEnum.SUCCESS.getResult();
				} else {
					return ServiceResultEnum.DB_ERROR.getResult();
				}
			} else {
				//订单此时不可执行关闭操作
				if (errorOrderNos.length() > 0 && errorOrderNos.length() < 100) {
					return errorOrderNos + "订单不能执行关闭操作";
				} else {
					return "你选择的订单不能执行关闭操作";
				}
			}
		}
		//未查询到数据 返回错误提示
		return ServiceResultEnum.DATA_NOT_EXIST.getResult();
	}

	@Override
	@Transactional
	public String saveOrder(UserVO user, List<ShoppingCartItemVO> myShoppingCartItems) {
		List<Integer> itemIdList = myShoppingCartItems.stream().map(ShoppingCartItemVO::getCartItemId).collect(Collectors.toList());
		List<Integer> goodsIds = myShoppingCartItems.stream().map(ShoppingCartItemVO::getGoodsId).collect(Collectors.toList());
		List<GoodsDetail> goods = goodsDetailMapper.selectByPrimaryKeys(goodsIds);
		Map<Integer, GoodsDetail> newBeeMallGoodsMap = goods.stream().collect(Collectors.toMap(GoodsDetail::getId, Function.identity(), (entity1, entity2) -> entity1));
		//判断商品库存
		for (ShoppingCartItemVO shoppingCartItemVO : myShoppingCartItems) {
			//查出的商品中不存在购物车中的这条关联商品数据，直接返回错误提醒
			if (!newBeeMallGoodsMap.containsKey(shoppingCartItemVO.getGoodsId())) {
				QingZhuException.fail(ServiceResultEnum.SHOPPING_ITEM_ERROR.getResult());
			}
			//存在数量大于库存的情况，直接返回错误提醒
			if (shoppingCartItemVO.getGoodsCount() > newBeeMallGoodsMap.get(shoppingCartItemVO.getGoodsId()).getStock()) {
				QingZhuException.fail(ServiceResultEnum.SHOPPING_ITEM_COUNT_ERROR.getResult());
			}
		}
		//删除购物项
		if (!CollectionUtils.isEmpty(itemIdList) && !CollectionUtils.isEmpty(goodsIds) && !CollectionUtils.isEmpty(goods)) {
			if (shoppingCartItemMapper.deleteBatch(itemIdList) > 0) {
				List<StockNumDTO> stockNumDTOS = BeanUtil.copyList(myShoppingCartItems, StockNumDTO.class);
				int updateStockNumResult = goodsDetailMapper.updateStockNum(stockNumDTOS);
				if (updateStockNumResult < 1) {
					QingZhuException.fail(ServiceResultEnum.SHOPPING_ITEM_COUNT_ERROR.getResult());
				}
				//生成订单号
				String orderNo = NumberUtil.genOrderNo();
				BigDecimal priceTotal = new BigDecimal("0.00");
				//保存订单
				OrderRecord order = new OrderRecord();
				order.setOrderNo(orderNo);
				order.setUserId(user.getUserId());
				order.setUserAddress(user.getAddress());
				//总价
				for (ShoppingCartItemVO shoppingCartItemVO : myShoppingCartItems) {
					priceTotal = priceTotal.add(shoppingCartItemVO.getSellingPrice().multiply(BigDecimal.valueOf(shoppingCartItemVO.getGoodsCount())));
				}
				if (priceTotal.intValue() < 1) {
					QingZhuException.fail(ServiceResultEnum.ORDER_PRICE_ERROR.getResult());
				}
				order.setTotalPrice(priceTotal);
				//todo 订单body字段，用来作为生成支付单描述信息，暂时未接入第三方支付接口，故该字段暂时设为空字符串
				String extraInfo = "";
//				order.setExtraInfo(extraInfo);
				//生成订单项并保存订单项纪录
				if (orderRecordMapper.insertSelective(order) > 0) {
					//生成所有的订单项快照，并保存至数据库
					List<OrderItem> orderItems = new ArrayList<>();
					for (ShoppingCartItemVO shoppingCartItemVO : myShoppingCartItems) {
						OrderItem orderItem = new OrderItem();
						//使用BeanUtil工具类将newBeeMallShoppingCartItemVO中的属性复制到newBeeMallOrderItem对象中
						BeanUtil.copyProperties(shoppingCartItemVO, orderItem);
						//NewBeeMallOrderMapper文件insert()方法中使用了useGeneratedKeys因此orderId可以获取到
						orderItem.setId(order.getId());
						orderItems.add(orderItem);
					}
					//保存至数据库
					if (orderItemMapper.insertBatch(orderItems) > 0) {
						//所有操作成功后，将订单号返回，以供Controller方法跳转到订单详情
						return orderNo;
					}
					QingZhuException.fail(ServiceResultEnum.ORDER_PRICE_ERROR.getResult());
				}
				QingZhuException.fail(ServiceResultEnum.DB_ERROR.getResult());
			}
			QingZhuException.fail(ServiceResultEnum.DB_ERROR.getResult());
		}
		QingZhuException.fail(ServiceResultEnum.SHOPPING_ITEM_ERROR.getResult());
		return ServiceResultEnum.SHOPPING_ITEM_ERROR.getResult();
	}

	@Override
	public OrderDetailVO getOrderDetailByOrderNo(String orderNo, Integer userId) {
		OrderRecord order = orderRecordMapper.selectByOrderNo(orderNo);
		if (order != null) {
			//todo 验证是否是当前userId下的订单，否则报错
			List<OrderItem> orderItems = orderItemMapper.selectByOrderId(order.getId());
			//获取订单项数据
			if (!CollectionUtils.isEmpty(orderItems)) {
				List<OrderItemVO> orderItemVOS = BeanUtil.copyList(orderItems, OrderItemVO.class);
				OrderDetailVO orderDetailVO = new OrderDetailVO();
				BeanUtil.copyProperties(order, orderDetailVO);
				orderDetailVO.setOrderStatusString(OrderStatusEnum.getOrderStatusEnumByStatus(orderDetailVO.getOrderStatus()).getName());
				orderDetailVO.setPayTypeString(PayTypeEnum.getPayTypeEnumByType(orderDetailVO.getPayType()).getName());
				orderDetailVO.setOrderItemVOS(orderItemVOS);
				return orderDetailVO;
			}
		}
		return null;
	}

	@Override
	public OrderRecord getOrderByOrderNo(String orderNo) {
		return orderRecordMapper.selectByOrderNo(orderNo);
	}

	@Override
	public PageResult getMyOrders(PageQueryUtil pageUtil) {
		int total = orderRecordMapper.getTotalOrders(pageUtil);
		List<OrderRecord> orders = orderRecordMapper.findOrderList(pageUtil);
		List<OrderListVO> orderListVOS = new ArrayList<>();
		if (total > 0) {
			//数据转换 将实体类转成vo
			orderListVOS = BeanUtil.copyList(orders, OrderListVO.class);
			//设置订单状态中文显示值
			for (OrderListVO orderListVO : orderListVOS) {
				orderListVO.setOrderStatusString(OrderStatusEnum.getOrderStatusEnumByStatus(orderListVO.getOrderStatus()).getName());
			}
			List<Integer> orderIds = orders.stream().map(OrderRecord::getId).collect(Collectors.toList());
			if (!CollectionUtils.isEmpty(orderIds)) {
				List<OrderItem> orderItems = orderItemMapper.selectByOrderIds(orderIds);
				Map<Integer, List<OrderItem>> itemByOrderIdMap = orderItems.stream().collect(groupingBy(OrderItem::getId));
				for (OrderListVO orderListVO : orderListVOS) {
					//封装每个订单列表对象的订单项数据
					if (itemByOrderIdMap.containsKey(orderListVO.getOrderId())) {
						List<OrderItem> orderItemListTemp = itemByOrderIdMap.get(orderListVO.getOrderId());
						//将NewBeeMallOrderItem对象列表转换成NewBeeMallOrderItemVO对象列表
						List<OrderItemVO> orderItemVOS = BeanUtil.copyList(orderItemListTemp, OrderItemVO.class);
						orderListVO.setOrderItemVOS(orderItemVOS);
					}
				}
			}
		}
		PageResult pageResult = new PageResult(orderListVOS, total, pageUtil.getLimit(), pageUtil.getPage());
		return pageResult;
	}

	@Override
	public String cancelOrder(String orderNo, Integer userId) {
		OrderRecord order = orderRecordMapper.selectByOrderNo(orderNo);
		if (order != null) {
			//todo 验证是否是当前userId下的订单，否则报错
			//todo 订单状态判断
			if (orderRecordMapper.closeOrder(Collections.singletonList(order.getId()), OrderStatusEnum.ORDER_CLOSED_BY_MALLUSER.getOrderStatus()) > 0) {
				return ServiceResultEnum.SUCCESS.getResult();
			} else {
				return ServiceResultEnum.DB_ERROR.getResult();
			}
		}
		return ServiceResultEnum.ORDER_NOT_EXIST_ERROR.getResult();
	}

	@Override
	public String finishOrder(String orderNo, Integer userId) {
		OrderRecord order = orderRecordMapper.selectByOrderNo(orderNo);
		if (order != null) {
			//todo 验证是否是当前userId下的订单，否则报错
			//todo 订单状态判断
			order.setStatus((byte) OrderStatusEnum.ORDER_SUCCESS.getOrderStatus());
			order.setUpdateTime(new Date());
			if (orderRecordMapper.updateByPrimaryKeySelective(order) > 0) {
				return ServiceResultEnum.SUCCESS.getResult();
			} else {
				return ServiceResultEnum.DB_ERROR.getResult();
			}
		}
		return ServiceResultEnum.ORDER_NOT_EXIST_ERROR.getResult();
	}

	@Override
	public String paySuccess(String orderNo, int payType) {
		OrderRecord order = orderRecordMapper.selectByOrderNo(orderNo);
		if (order != null) {
			//todo 订单状态判断 非待支付状态下不进行修改操作
			order.setStatus((byte) OrderStatusEnum.OREDER_PAID.getOrderStatus());
			order.setPayType((byte) payType);
			order.setPayStatus((byte) PayStatusEnum.PAY_SUCCESS.getPayStatus());
			order.setPayTime(new Date());
			order.setUpdateTime(new Date());
			if (orderRecordMapper.updateByPrimaryKeySelective(order) > 0) {
				return ServiceResultEnum.SUCCESS.getResult();
			} else {
				return ServiceResultEnum.DB_ERROR.getResult();
			}
		}
		return ServiceResultEnum.ORDER_NOT_EXIST_ERROR.getResult();
	}

	@Override
	public List<OrderItemVO> getOrderItems(Integer id) {
		OrderRecord order = orderRecordMapper.selectByPrimaryKey(id);
		if (order != null) {
			List<OrderItem> orderItems = orderItemMapper.selectByOrderId(order.getId());
			//获取订单项数据
			if (!CollectionUtils.isEmpty(orderItems)) {
				List<OrderItemVO> orderItemVOS = BeanUtil.copyList(orderItems, OrderItemVO.class);
				return orderItemVOS;
			}
		}
		return null;
	}
}